package com.cium.aqie.highOrderFunction

/**
 * @Function: 闭包：函数式编程
 * @Author: aqie
 * @Date: 2019/9/2 9:27
 */
val string = "HelloWorld"

/**
 * 返回一个无参 无返回值函数
 * 调用一次返回函数 打印值+1
 */
fun makeFun(): ()->Unit{
    var count = 0
    return fun(){
        println(++count)
    }
}

/**
 * 普通 斐波那契数列
 */
fun fib(): ()->Long{
    var first = 0L
    var second = 1L
    return fun():Long{
        val result = second
        second += first
        first = second - first
        return result
    }
}
/**
 * 斐波那契函数
 * @return 迭代器
 */
fun fibonacci(): Iterable<Long>{
    var first = 0L
    var second = 1L
    return Iterable {
        object : LongIterator(){
            override fun nextLong(): Long {
                val result = second
                second += first
                first = second - first
                return result
            }
            override fun hasNext() = true
        }
    }
}

// 看不懂的版本
fun add(x: Int) = fun(y: Int) = x + y

fun addSimple(x: Int): (Int)-> Int{
    // 函数内部定义类
    data class Person(val name: String, val age: Int)

    // 函数内部定义函数
    return fun(y: Int): Int{
        return x + y
    }
}

fun main() {
    val x : ()->Unit = makeFun()
    x()
    x()
    val y = fib()
    println(y())
    println(y())
    println(y())

    for(i in fibonacci()){
        if (i > 100) break
        print("$i ")
    }

    val add5 = add(5)
    println(add5(2))

    val addSimple = addSimple(5)
    println(addSimple(2))
}